<template>
  <div class="container">
    <div>
      <el-card class="invoice-instructions mb-2">
        <div class="title">
          <h3>
            <i class="el-icon-info"></i>
            {{ $language.local("Notice") }}:
          </h3>
        </div>
        <ol class="info-body">
          <li>工作内容描述不录入具体人员姓名、金额数字等详细内容；</li>
          <li>
            工作内容的描述不能有如下字眼：
            <em class="red">工资、补贴、津贴、福利、劳务、销售、经纪、工程安装、装修、装饰、清包工</em>
            等字眼；
          </li>
          <p>如有疑问请联系平台客服人员。</p>
        </ol>
      </el-card>
    </div>

    <el-form
      :disabled="isCheck"
      :model="formData"
      class="pr-2 grid-flex"
      label-width="6rem"
      ref="taskInfoRef"
      status-icon
    >
      <el-form-item
        :error="uploadFileError"
        :label="$language.local('TskEmpFile')"
        :rules="TskEmpFileRule"
        class="upload-file"
        prop="TskEmpFile"
      >
        <upload-file
          :name="formData.TskEmpFile"
          :on-success="onSuccess"
          :showFileList="true"
          v-model="formData.TskEmpFile"
        ></upload-file>
        <a
          href="http://demo.xinyueai.com/admin/static/template/tasktemplate.xlsx"
          target="_blank"
        >
          <span class="el-icon-download"></span>
          下载模板
        </a>
      </el-form-item>
    </el-form>
    <div class="mb-2">
      <xy-table
        :list="employees"
        v-if="employees.length > 0"
      >
        <template #addItem>
          <span hidden></span>
        </template>
        <template #operation>
          <span hidden></span>
        </template>
        <template #pagination>
          <span hidden></span>
        </template>
      </xy-table>
    </div>

    <div class="form-footer">
      <el-button
        @click="reload()"
        size="mini"
      >
        {{
        $language.local("返回")
        }}
      </el-button>
      <template v-if="api.action == 'Check'">
        <el-button
          @click="showReasonDialog"
          class
          size="mini"
          type="danger"
        >{{ $language.local("不通过") }}</el-button>
        <el-button
          @click="onCheck(1)"
          size="mini"
          type="success"
        >
          {{
          $language.local("通过")
          }}
        </el-button>

        <!-- #region 审核原因 -->
        <el-dialog
          :title="$language.local('Reason')"
          :visible.sync="inputReasonVisible"
        >
          <el-form
            :model="formData"
            :rules="$rules"
            ref="ReasonRef"
            status-icon
          >
            <el-form-item prop="Reason">
              <xy-input
                clearable
                v-model="formData.Reason"
              ></xy-input>
            </el-form-item>
          </el-form>
          <div
            class="dialog-footer"
            slot="footer"
          >
            <el-button
              @click="onCheck(2)"
              size="mini"
              type="primary"
            >确 定</el-button>
          </div>
        </el-dialog>
        <!-- #endregion -->
      </template>
      <el-button
        :disabled="!!uploadFileError"
        @click="onSubmit('taskInfoRef')"
        size="mini"
        type="primary"
        v-else
      >{{ $language.local("确定") }}</el-button>
    </div>
  </div>
</template>

<script>
import API from "../../plugins/api";
export default {
  inject: ["reload"],
  data() {
    const validateEndTime = (rule, value, callback) => {
      if (!this.formData.BegTime) {
        callback(new Error("请输入开始时间！"));
        return;
      }
      const begTime = new Date(this.formData.BegTime);
      const endTime = new Date(value);
      if (endTime.compare(begTime)) {
        callback();
      } else {
        callback(new Error("请输入大于开始时间的日期！"));
      }
    };
    const validateTskEmpFile = (rule, value, callback) => {
      if (this.uploadFileError === "") {
        callback();
      } else {
        callback(new Error(this.uploadFileError));
      }
    };
    return {
      user: this.$store.getters.user,
      api: new API("/api/ServiceProject/Create"),
      merchant: null,
      formData: {
        MID: null,
        SID: "",
        ServiceType: "",
        PostName: "",
        projectName: "",
        recruitPerson: 1,

        WorkContent: "",
        PerformanceFeeSettlementRules: "",

        ServiceName: "",
        BegTime: new Date().toLocaleDateString(),
        EndTime: "",
        Amount: null,
        TskEmpFile: "",
        attFileName: null,
        attFilePath: null,
        SettlementModes: "",
        otherSettlementModes: "",
        RecruitmentRequirements: "",
        checker: "",
        checkstatus: "",

        Reason: "",
      },
      attFileList: null,
      isCheck: false,
      inputReasonVisible: false,
      settlementModes: [
        {
          value: 1,
          label: "按项目工作时间结算",
        },
        {
          value: 2,
          label: "按项目工作成果结算",
        },
        {
          value: 3,
          label: "按项目完工进度结算",
        },
        {
          value: 4,
          label: "其它方式",
        },
      ],
      EndTimeRule: [
        { required: true, message: "不能为空", trigger: "blur" },
        { validator: validateEndTime, trigger: "blur" },
      ],
      TskEmpFileRule: [
        { required: true, message: "不能为空", trigger: "blur" },
        { validator: validateTskEmpFile, trigger: "blur" },
      ],
      ServiceContent: "",
      ServiceContents: [],
      uploadFileError: "",
      employees: [],

    };
  },
  watch: {
    "formData.ServiceType": {
      async handler(newValue) {
        try {
          const response = await this.$http.get(
            `/api/ServiceProject/GetContentModel?ServiceContent=${newValue}`
          );
          console.log(response);
          this.ServiceContents = response.data.Data;
        } catch (error) {
          console.log(error);
        }
      },
    },
  },
  created() {
    this.onConfig();
  },
  methods: {
    async onConfig() {
      let { apiName, id } = this.$route.query;

      if (!apiName || !id) {
        return;
      }
      this.api = new API(apiName);
      if (this.api.action == "Check") {
        this.isCheck = true;
      }

      let item = null;
      try {
        item = await this.getServiceProjectById(id);
      } catch (error) {
        console.error(error);
        this.$router.replace("/ServiceProjectList");
        throw error;
      }
      console.log(item);
      if (!item) {
        console.log(123);
        this.$router.replace("/ServiceProjectList");
        return;
      }

      this.formData = {
        ...this.formData,
        ...item,
      };
    },
    async getServiceProjectById(id) {
      let response = await this.$http.get(`/api/ServiceProject/GetModel/${id}`);
      return response.data.Data;
    },
    async onSuccess(e) {
      console.log(e);
      this.formData.attFileName = e.docname;
      let query = {
        ExcelUrl: e.docurl,
        mid: this.user.branchid,
      };
      try {
        let response = await this.$http.post(
          "/api/ServiceProject/CheckTskData",
          null,
          query
        );
        if (response.data.Code !== 200) {
          throw response;
        }
        console.log(response);
        this.employees = [response.data.Data];

      } catch (error) {

        this.uploadFileError = error.data.Message;

        throw error;
      }
    },
    showReasonDialog() {
      this.inputReasonVisible = true;
    },
    async onCheck(check) {
      if (check == 2) {
        await this.$refs["ReasonRef"].validate();
      }
      let response = await this.$http.post(
        `/api/ServiceProject/Check/${this.formData.ID}?checkstatus=${check}&Reason=${this.formData.Reason}`
      );
      console.log(response);
      this.$message.success("审核成功");
      this.$router.go(-1);
    },
    async onSubmit(formName) {
      console.log(this.user);
      console.log(this.formData);
      await this.$refs[formName].validate();
      let { amount, begindate, taskname, tasktype, enddate, workcontent } = this.employees[0];
      this.formData = { ...this.formData,
        Amount: amount,
        BegTime: begindate,
        EndTime: enddate,
        MID: this.user.branchid,
        projectName: taskname,
        ServiceType: tasktype,
        WorkContent: workcontent,
        ...this.employees[0] };
      console.log(this.formData);
      try {
        let response = await this.$http.post(
          "/api/ServiceProject/Create",
          this.formData
        );
        console.log(response);
        this.reload();
      } catch (error) {
        console.error(error);
      }
    },
    ServiceContentChange(e) {
      console.log(e);
      this.formData.WorkContent = e.ModelContent;
      this.formData.RecruitmentRequirements = e.RRContent;
    },
    midChange(e) {
      console.log(e);
    },
  },
};
</script>

<style lang="less" scoped>
.el-select {
  width: 100%;
}
.row {
  align-items: flex-start;
  width: 100%;
}
.select-servicecontent {
  color: gray;
}
.invoice-instructions {
  margin: 0;
  padding: 0 2rem;
  .info-body {
    // display: flex;
    // flex-wrap: wrap;
    li {
      font-size: 12px;
      // width: 50%;
      margin-bottom: 1ex;
    }
  }
}
// .xy-table {
//   // padding-bottom: 5rem;
//   position: relative;
// }
</style>
